package cc.magicjson.mall.member.application.service;

import cc.magicjson.mall.member.application.command.RegisterMemberCommand;
import cc.magicjson.mall.member.domain.model.Member;
import cc.magicjson.mall.member.domain.model.MemberAggregate;
import cc.magicjson.mall.member.domain.repository.MemberRepository;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MemberApplicationService {
	private final MemberRepository memberRepository;
	private final ApplicationEventPublisher eventPublisher;

	public MemberApplicationService(MemberRepository memberRepository, ApplicationEventPublisher eventPublisher) {
		this.memberRepository = memberRepository;
		this.eventPublisher = eventPublisher;
	}

	@Transactional
	public String registerMember(RegisterMemberCommand command) {
		if (memberRepository.findByUsername(command.username()) != null) {
			throw new IllegalArgumentException("Username already exists");
		}

//		Member member = new Member();
		Member member = Member.builder()
				.username(command.username())
				.email(command.email())
				.password(command.password()).build();
//		member.setUsername(command.getUsername());
//		member.setEmail(command.getEmail());
//		member.setPassword(command.getPassword());  // 注意：实际应用中应该对密码进行加密处理

		memberRepository.save(member);
		MemberAggregate memberAggregate = new MemberAggregate(member);

		// 发布领域事件
		memberAggregate.getDomainEvents().forEach(eventPublisher::publishEvent);
		memberAggregate.clearDomainEvents();

		return member.getId();
	}

	// 其他应用服务方法...
}